package com.yixun.qfbao.job;

import java.util.Calendar;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.WechatTemplateMessageService;
import com.yixun.qfbao.model.WxmsgFailure;
import com.yixun.qfbao.model.dto.WxmsgFailureDto;
import com.yixun.qfbao.model.enums.SendStatusEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.service.WxmsgFailureService;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.TemplateMessageResult;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;

/**
 * 一句话功能简述〉 〈功能详细描述〉
 * 
 * @author linyao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Component
public class SendWxMsgAgainJob {
	private static Logger logger = LoggerFactory.getLogger(SendWxMsgAgainJob.class);

	@Autowired
	private WxAccessTokenCacheUtils wxAccessTokenCacheUtils;
	@Autowired
	private WxmsgFailureService wxmsgFailureService;
	@Autowired
	private WechatTemplateMessageService wechatTemplateMessageService;

	@Value("${spring.datasource.url}")
	private String dataSource;
	
	@Scheduled(cron = "0 0/5 * * * ?")
	public void sendWxMsgAgainJob() {
		logger.warn("5分钟处理一次微信失败消息 start..........");
		logger.info("SendWxMsgAgainJob->SendWxMsgAgainJob->dataSource:{}", dataSource);
		String ymd = DateUtils.DateToString(Calendar.getInstance().getTime(), DateStyle.YYYY_MM_DD);
		String timeBefore = ymd + " 00:00:00";
		String timeAfter = ymd + " 23:59:59";
		String companyUuid = "";
		long sqlStartTime = System.currentTimeMillis();
		logger.info(" startTime===========> "+sqlStartTime);
		List<WxmsgFailureDto> failureCompanyList = wxmsgFailureService.getFailureCompany(timeBefore);
		long sqlEndTime = System.currentTimeMillis();
		logger.info(" sqlendTime===========> {}"+sqlEndTime);
		logger.info("微信失败消息sql查询 总共耗时：------------> :"+(sqlEndTime-sqlStartTime));
		logger.info("==================== {}",JSONObject.toJSONString(failureCompanyList));
		logger.info("SendWxMsgAgainJob->SendWxMsgAgainJob->failureCompanyList:{}", 
				CollectionUtils.isEmpty(failureCompanyList)? "": JSONObject.toJSON(failureCompanyList).toString());
		if(null != failureCompanyList && failureCompanyList.size() > 0){
			for(WxmsgFailureDto failureDto: failureCompanyList){
				if(null != failureDto && StringUtils.isNotEmpty(failureDto.getCompanyUuid())){
					companyUuid = failureDto.getCompanyUuid();

					WxmsgFailureDto wxmsgFailureDto = new WxmsgFailureDto();
					wxmsgFailureDto.setCompanyUuid(companyUuid);
					wxmsgFailureDto.setSendStatus(SendStatusEnum.RESEND.getNo());
					wxmsgFailureDto.setIsResend(true);
					wxmsgFailureDto.setCreateTimeBefore(DateUtils.StringToDate(timeBefore, DateStyle.YYYY_MM_DD_HH_MM_SS));
					wxmsgFailureDto.setCreateTimeAfter(DateUtils.StringToDate(timeAfter, DateStyle.YYYY_MM_DD_HH_MM_SS));
					List<WxmsgFailure> failureList = wxmsgFailureService.selectListByDto(wxmsgFailureDto);
					logger.info("SendWxMsgAgainJob->SendWxMsgAgainJob->companyUuid:{}", companyUuid);
					logger.info("SendWxMsgAgainJob->SendWxMsgAgainJob->timeBefore:{}", timeBefore);
					logger.info("SendWxMsgAgainJob->SendWxMsgAgainJob->timeAfter:{}", timeAfter);
					logger.info("SendWxMsgAgainJob->SendWxMsgAgainJob->failureList:{}", 
							CollectionUtils.isEmpty(failureList)? "": JSONObject.toJSON(failureList).toString());
					if(null != failureList && failureList.size() > 0){
						wxAccessTokenCacheUtils.remove(companyUuid, SystemIdEnum.ASSISTANT.getCode());
						wxAccessTokenCacheUtils.remove(companyUuid, SystemIdEnum.AGENCY_h5.getCode());
						wxAccessTokenCacheUtils.remove(companyUuid, SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode());
						String assistantToken = wxAccessTokenCacheUtils.getAccessTokenBySystemId(companyUuid, SystemIdEnum.ASSISTANT.getCode(), null);
						String agencyToken = wxAccessTokenCacheUtils.getAccessTokenBySystemId(companyUuid, SystemIdEnum.AGENCY_h5.getCode(), null);
						String weappAgencyWxAccountToken = wxAccessTokenCacheUtils.getAccessTokenBySystemId(companyUuid, SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(), null);
						logger.warn("公司:"+companyUuid + ",assistant toke = " + assistantToken + ", agency token = " + agencyToken);
						for(WxmsgFailure wf: failureList){
							String receiveContent = wf.getReceiveContent();
							String originalResult = wf.getResult();
							if(!originalResult.contains("40001")
							&& !originalResult.contains("system error")){
								continue;
							}
							logger.warn("send failure msg Job start accesstoken {}, content {}", assistantToken, receiveContent);
							TemplateMessageResult result;
							//如果是分销小程序对应的公众号，要使用分销小程序对应公众号的token
							if(SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode().equals(wf.getSystemId())) {
								result = wechatTemplateMessageService.sendTemplate(weappAgencyWxAccountToken, receiveContent);
							}else if(SystemIdEnum.AGENCY_h5.getCode().equals(wf.getSystemId())){
								result = wechatTemplateMessageService.sendTemplate(agencyToken, receiveContent);
							}else {
								result = wechatTemplateMessageService.sendTemplate(assistantToken, receiveContent);
							}
							WxmsgFailureDto wfDto = new WxmsgFailureDto();
							wfDto.setId(wf.getId());
							if("ok".equals(result.getErrmsg().toLowerCase())) {
								wfDto.setSendStatus(SendStatusEnum.SUCCESS.getNo());
							}else{
								wfDto.setSendStatus(SendStatusEnum.FAILURE.getNo());
							}
							wfDto.setRepeatResult(JSONObject.toJSONString(result));
							wfDto.setIsResend(false);
							wxmsgFailureService.update(wfDto);
							logger.warn("send failure msg Job end result {}", JSONObject.toJSONString(result));
						}
					}
				}
			}
		}
		logger.warn("5分钟处理一次微信失败消息 end..........");
	}
}
